<?php
/**
 * @Author: gan
 * @Description: 梦网短信
 * @File:  MwImpl
 * @Version: 1.0.0
 * @Date: 2021/12/27 9:15 上午
 */
declare(strict_types=1);

namespace RX\Component\Sms\Impl;

use RX\Enums\SmsEnum;
use RX\Exception\BizException;
use RX\Helpers\StringHelper;
use RX\Traits\CurlTrait;

class MwImpl implements SmsInterface
{
    use CurlTrait;

    private string $host;
    private string $userId;
    private string $password;
    private string $content;
    public const  SEND_SINGLE = "/sms/v2/std/send_single";

    public function __construct(array $config = [])
    {
        if (empty($config)) {
            $config = StringHelper::config('sms.mw');
        }
        $this->host     = $config["host"];
        $this->userId   = $config["userId"];
        $this->password = $config["password"];
        $this->content  = $config["content"];
    }

    public function send(string $mobile, string $sign, string $template, array $templateParams = [])
    {
        $url      = $this->host . self::SEND_SINGLE;
        $time     = date('mdHis');
        $password = md5(strtoupper($this->userId) . '00000000' . $this->password . $time);
        $content  = urlencode($this->content);
        $data     = [
            'userid'    => $this->userId,
            'pwd'       => $password,
            'mobile'    => $mobile,
            'content'   => $content,
            'timestamp' => $time,
        ];
        $result   = $this->postCurl($url, $data);
        $result   = json_decode($result, true);
        if (!isset($result['result']) || $result['result'] != 0) {
            $msg = $result['desc'] ? urldecode($result['desc']) : null;
            throw new BizException(SmsEnum::class, SmsEnum::SMS_FAIL, $msg);
        }
        return $result;
    }
}
